<template>
  <div ref="mapContainer"></div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick,defineExpose } from 'vue'
import AMapLoader from '@amap/amap-jsapi-loader'
import { ElMessage } from 'element-plus'

const location = ref('Beijing');
const longitude = ref(null);  // 存储经度
const latitude = ref(null);   // 存储纬度

// 使用 defineExpose 暴露子组件的变量或方法
defineExpose({
  location,
  longitude,
  latitude
});


const mapContainer = ref(null)
let map = null

onMounted(() => {
  nextTick(() => {
    window._AMapSecurityConfig = {
      securityJsCode: '02c74949d973a3d48dea2811ce9c126a'
    }

    AMapLoader.load({
      key: '82903b8b4ecaad2c03dfa5478cfa5bf8',
      version: '2.0',
      plugins: ['AMap.Scale']
    }).then((AMap) => {
      map = new AMap.Map(mapContainer.value, {
        resizeEnable: true,
        zoom: 15
      })

      AMap.plugin('AMap.Geolocation', () => {
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,
          timeout: 10000,
          offset: [10, 20],
          zoomToAccuracy: true,
          position: 'RB'
        })
        map.addControl(geolocation)
        geolocation.getCurrentPosition((status, result) => {
          status === 'complete' ? onComplete(result) : onError(result)
        })
      })
    })
  })
})

onUnmounted(() => {
  map?.destroy()
})

function onComplete(data) {
  console.log(data)
  // 提取经纬度
  const { lng, lat } = data.position

  // 更新经纬度
  longitude.value = lng;
  latitude.value = lat;

  // 打印经纬度到控制台
  console.log('经度:', lng)
  console.log('纬度:', lat)

  // 显示提示消息
  // ElMessage.success(`定位成功！经度: ${lng}, 纬度: ${lat}`)
  ElMessage('定位成功')
}

function onError(data) {
  ElMessage(data.message)
}
</script>

<style scoped>
div {
  width: 100%;
  height: 400px;
  background-color: #f0f0f0;
}
</style>
